<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :http-request="upload"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="photo" :src="photo" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-show="showProcess" status="success" type="line" :percentage="percent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID2qypPx2LCpCuMWPNCk482f1DALFupp30', // 身份识别ID
  SecretKey: 'va09yX4KJ88sa03GDtIRPVLBlqAE0X2G' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    photo: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showProcess: false,
      percent: 0
    }
  },
  methods: {
    upload(params) {
      this.showProcess = true
      cos.putObject({
        Bucket: 'hr-admin-tamplete-1305861554', /* 必须 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (data.statusCode === 200) {
          setTimeout(() => {
            // this.imageUrl = `https://${data.Location}`
            this.$emit('update:photo', `https://${data.Location}`)
            this.showProcess = false
          }, 500)
        }
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
